<template>
  <div class="">
    <div class="c-ph24 c-p c-w100 c-flex-row c-justify-sb c-bg-white c-aligni-center c-bd-b1-f6">
      <div class="c-contextX-scroll c-ws-n c-bg-white" id="cityScroll">
        <div v-if="comeFrom==1">
          <div v-for="(item, index) in cityArr" :key="index" class="c-inlineblack c-textAlign-c c-mr40 c-fs24 c-fc-xblack" @click="changeRegionType(index,item.xauId)">
            <span class="c-inlineblack c-ph5 c-pt20 c-pb12">
              {{item.name}}
            </span>
            <div v-if="regionIndex == index" class="c-ww32 c-hh6 theme-bg-gradient c-br4 c-m-0auto"></div>
          </div>
        </div>
        <div class="" v-else>
          <div v-for="(item) in cityArr" :key="item.areaUserApplicationId" :id="'city'+item.areaUserApplicationId" class="c-inlineblack c-textAlign-c c-mr40 c-fs24 c-fc-xblack" @click="changeCity(item.areaUserApplicationId, item)">
            <span class="c-inlineblack c-ph5 c-pt20 c-pb12">
              {{item.name}}
            </span>
            <div v-if="selectItem.areaUserApplicationId == item.areaUserApplicationId" class="c-ww32 c-hh6 theme-bg-gradient c-br4 c-m-0auto"></div>
          </div>
        </div>
      </div>
      <span class="iconfont c-pl14 c-pr24 c-fs30 c-fc-sblack section-icon" @click="showMoreInfo = true" v-if="comeFrom == 0">&#xe8a3;</span>
    </div>
    <div v-if="selectItem.auditStatus == 1" class="c-ph24 c-textAlign-c c-mt100">
      <div class="c-ww80 c-m-0auto">
        <img src="@/assets/i/wap/newAreaAgent/data-checking.png" class="c-w100" alt="">
      </div>
      <div class="c-fs26 c-fc-gray c-mt28">【{{selectItem.role | roleFilter}}】身份审核中，请耐心等待</div>
    </div>
    <div v-else class="c-ph24 c-mt30 c-mb80">
      <div v-if="selectItem.areaId > 0 && comeFrom == 0" class="c-box-shadow8 c-pv30 c-flex-row c-fs28 c-fc-xblack c-br20">
        <div class="c-w50 c-h100 c-flex-column c-justify-sb c-aligni-center">
          <p class="c-fw-b theme-fc">{{selectItem.role | roleFilter}}</p>
          <p class="c-fs20 c-fc-sblack c-mt12">身份</p>
        </div>
        <div class="c-w50 c-h100 c-flex-column c-justify-sb c-aligni-center">
          <p class="c-fw-b">{{totalRegisterNum || 0}}</p>
          <p class="c-fs20 c-fc-sblack c-mt12">总注册用户(人)</p>
        </div>
      </div>
      <div v-if="comeFrom == 1" class="c-box-shadow8 c-pt52 c-flex-row c-fs28 c-fc-xblack c-br20">
        <div class="c-w50 c-h100 c-flex-column c-justify-sb c-aligni-center c-pt6 c-pb32">
          <p class="c-fw-b theme-fc" v-if="cityArr && !!cityArr[regionIndex]">{{cityArr[regionIndex].regionType == 1 ? '省代理' : cityArr[regionIndex].regionType == 2 ? '市代理' : '区代理'}}</p>
          <p class="c-fs20 c-fc-sblack c-mt12">身份</p>
        </div>
        <div class="c-w50 c-h100 iconfont">
          <img src="@/assets/i/wap/newAreaAgent/agent.png" class="c-ww100 c-m-0auto">
        </div>
      </div>
      <div :class="comeFrom == 0 ? 'c-bd-b1-f0' : ''">
        <div class="c-flex-row c-justify-sb c-aligni-end c-fc-xblack" :class="selectItem.areaId > 0 ? 'c-mt40' : 'c-mt30'">
          <div class="c-fs26 c-flex-row c-aligni-center"><span :class="leftBorderCss"></span><span>当前数据</span></div>
          <div v-if="comeFrom == 1" class="c-flex-row c-aligni-center">
            <p @click="showSelectOption = true"><span class="c-fs20 c-mr10">{{selectTimeData.label || selectTimeData.value}}</span><i class="iconfont c-fs16">&#xe604;</i></p>
            <span v-if="isNoAllCity" class="c-fs20 c-fc-f2 c-pl32">|</span>
            <p class="c-pl32" @click="goAreaIncome"><span class="c-fs20 c-mr10">月度奖</span><i class="iconfont c-fs16">&#xe908;</i></p>
          </div>
          <div v-else class="c-flex-row c-aligni-center">
            <p @click="showSelectOption = true"><span class="c-fs20 c-mr10">{{selectTimeData.label || selectTimeData.value}}</span><i class="iconfont c-fs16">&#xe604;</i></p>
            <span v-if="isNoAllCity" class="c-fs20 c-fc-f2 c-pl32">|</span>
            <p class="c-pl32" v-if="isNoAllCity" @click="linkToIncome"><span class="c-fs20 c-mr10">收入明细</span><i class="iconfont c-fs16">&#xe908;</i></p>
          </div>
        </div>

        <div v-if="comeFrom==1">
          <div class="c-flex-row c-justify-sb c-pt40">
            <div class="c-w50">
              <div class="c-fs26 c-fw-b">{{currentData.userMoney}}</div>
              <div class="c-pt8 c-fs20 c-fc-gray">本人直推业绩(元)</div>
            </div>
            <div class="c-w50">
              <div class="c-fs26 c-fw-b">{{currentData.areaMoney}}</div>
              <div class="c-pt8 c-fs20 c-fc-gray">区域业绩(元)</div>
            </div>
          </div>
          <div class="c-flex-row c-justify-sb c-pt40">
            <div class="c-w50">
              <div class="c-fs26 c-fw-b">{{currentData.areaUserCount}}</div>
              <div class="c-pt8 c-fs20 c-fc-gray">区域代理(人)</div>
            </div>
            <div class="c-w50">
              <div class="c-fs26 c-fw-b">{{currentData.ratioValue}}%</div>
              <div class="c-pt8 c-fs20 c-fc-gray">奖金比例</div>
            </div>
          </div>
          <div class="c-flex-row c-justify-sb c-pt40">
            <div class="c-w50">
              <div class="c-fs26 c-fw-b">{{currentData.totalUserMoney}}</div>
              <div class="c-pt8 c-fs20 c-fc-gray">区域代理直推业绩(元)</div>
            </div>
            <div class="c-w50">
              <div class="c-fs26 c-fw-b">{{currentData.monthMoney}}</div>
              <div class="c-pt8 c-fs20 c-fc-gray">月度奖</div>
            </div>
          </div>
        </div>
        <div class="c-flex-row c-flexw-wrap c-pv10 c-pl20" v-else>
          <div :class="dataParentCss">
            <p :class="dataNumberCss">{{currentData.registerNum || 0}}</p>
            <p :class="dataTextCss">新注册用户(人)</p>
          </div>
          <div :class="dataParentCss" class="c-pl40">
            <p :class="dataNumberCss">{{currentData.payNum || 0}}</p>
            <p :class="dataTextCss">付费用户数(人)</p>
          </div>
          <div v-for="(item, index) in currentData.data" class="c-flex-row c-flexw-wrap c-w100" :key="index">
            <template v-if="item.prodType ==1">
              <div :class="dataParentCss">
                <p :class="dataNumberCss">{{item.orderNum || 0}}</p>
                <p :class="dataTextCss">VIP订单数(单)</p>
              </div>
              <div :class="dataParentCss" class="c-pl40">
                <p :class="dataNumberCss">{{item.buyMoney || 0}}</p>
                <p :class="dataTextCss">VIP订单金额(元)</p>
              </div>
            </template>
            <template v-else-if="companyAuth.enableSvipModule == 1">
              <div :class="dataParentCss">
                <p :class="dataNumberCss">{{item.orderNum || 0}}</p>
                <p :class="dataTextCss">SVIP订单数(单)</p>
              </div>
              <div :class="dataParentCss" class="c-pl40">
                <p :class="dataNumberCss">{{item.buyMoney || 0}}</p>
                <p :class="dataTextCss">SVIP订单金额(元)</p>
              </div>
            </template>
          </div>
          <div :class="dataParentCss" v-if="selectItem.areaId > -1 && currentData.reward">
            <p :class="dataNumberCss">{{currentData.reward ? currentData.reward.reward : 0}}</p>
            <p :class="dataTextCss">{{currentData.reward.type == 1 ? `月达标奖` : `季度达标奖`}}(元)</p>
          </div>
        </div>
      </div>

      <div v-if="comeFrom ==0 ">
        <div v-if="selectItem.areaId <= -1" class="">
          <!-- 全国的时候才出现 年终奖金池 -->
          <div class="c-bd-b1-f0 c-fs24 c-fc-xblack c-pv30 c-flex-row c-aligni-center">
            <div class="c-ww130"><img src="@/assets/i/wap/newAreaAgent/award.png" class="c-w100" alt=""></div>
            <span class="c-ml14">预计<span class="theme-fc">{{currentData.rewardMoney || 0}}</span>元</span>
          </div>
          <div class="c-fs20 c-fc-sblack c-mt30 c-mb64" v-if="currentData.notice">
            <p class="c-mb20">奖金池公告：</p>
            <div class="c-p" ref="noticeDiv">
              <span class="c-lh48 c-wb-ba" ref="noticeSpan">{{currentData.notice}}</span>
            </div>
          </div>
        </div>
        <div v-else>
          <div class="c-bd-b1-f0 c-aligni-end c-fc-xblack c-mt30">
            <div class="c-flex-row c-justify-sb c-aligni-center">
              <div class="c-fs26 c-flex-row c-aligni-center"><span :class="leftBorderCss" class=""></span><span>服务奖</span></div>
              <span @click="linkToCash" class="c-lh"><span class="c-fs20 c-mr10">去提现</span><i class="iconfont c-fs16">&#xe908;</i></span>
            </div>
            <div class="c-flex-row c-flexw-wrap c-pv10 c-pl20">
              <div :class="dataParentCss">
                <p :class="dataNumberCss">{{serviceAwardData.balance || 0}}</p>
                <p :class="dataTextCss">本月奖金(元)</p>
              </div>
              <div :class="dataParentCss" class="c-pl40">
                <p :class="dataNumberCss">{{serviceAwardData.withdrawedMoney || 0}}</p>
                <p :class="dataTextCss">累计奖金(元)</p>
              </div>
            </div>
          </div>
          <div v-for="(item, index) in achieveAwardData" :key="index" class=" c-aligni-end c-fc-xblack c-mt30"
            :class="index < achieveAwardData.length-1 ? 'c-bd-b1-f0' : ''">
            <div class="c-flex-row c-aligni-center">
              <span :class="leftBorderCss"></span>
              <span class="c-fs26">{{item.type | achTypeFilter}}</span>
            </div>
            <div class="c-flex-row c-flexw-wrap c-pv10 c-pl20">
              <div :class="dataParentCss">
                <p :class="dataNumberCss">{{parseInt(item.targetPeople) || '--'}}</p>
                <p :class="dataTextCss">目标(人)</p>
              </div>
              <div :class="dataParentCss" class="c-pl40">
                <p :class="dataNumberCss">{{item.finishNum || '--'}}</p>
                <p :class="dataTextCss">已完成(人)</p>
              </div>
              <div :class="dataParentCss">
                <p :class="dataNumberCss">{{item.achievementNum || '--'}}</p>
                <p :class="dataTextCss">已达标正会长</p>
              </div>
              <div :class="dataParentCss" class="c-pl40">
                <p :class="dataNumberCss">{{item.achievementSubNum || '--'}}</p>
                <p :class="dataTextCss">已达标副会长</p>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
    <!-- 申请会长图标 -->
    <div class="c-pf c-p-r24 c-p-b60">
      <div class="c-bg-white c-brp50">
        <div @click="linkToApplyAreaAgent" class="c-mb20 c-ww80 c-hh80 theme-bg-gradient theme-box-shadow c-fs20 c-fc-white c-flex-row c-justify-center c-aligni-center c-brp50">
          <span class="c-textAlign-c">申请<br>会长</span>
        </div>
      </div>
      <div @click="linkToApplyRecords" class=" c-ww80 c-hh80 c-bg-white c-box-shadow7 c-fs20 c-fc-xblack c-flex-row c-justify-center c-aligni-center c-brp50">
        <span class="c-textAlign-c">申请<br>进度</span>
      </div>
    </div>
    <!-- 点击图标查看跟多的城市信息 -->
    <cj-popup v-model="showMoreInfo" position="bottom">
      <div class="c-bg-white c-ph48 c-maxh600 c-contexty-auto">
        <div v-for="(item, index) in cityArr" :key="item.areaUserApplicationId"
          class="c-fs24 c-fc-222 c-pv30 " :class="{'theme-fc': selectItem.areaUserApplicationId == item.areaUserApplicationId, 'c-bd-b1-mgray': index < cityArr.length-1}"
          @click="changeCity(item.areaUserApplicationId, item)">
          {{item.name}}
        </div>
      </div>
    </cj-popup>
    <!-- 时间筛选 -->
    <time-popup :showPopup="showSelectOption" @clickConfirm="getData" @clickCancel="getData" :comeFrom = "comeFrom"></time-popup>
  </div>
</template>
<script>
import { utilJs } from "@/utils/common.js";
import timePopup from '@/components/homePage/newAreaAgent/selectTimePopup.vue'
import validateVipType from './validateVipType'
let selectItemVal = {};
let fromPath = '';
export default {
  name: 'areaAgent',
  mixins: [validateVipType],
  components: {
    timePopup
  },
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : 'mb5_default',
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      cityArr: [],
      selectItem: {},
      timer: '',
      showMoreInfo: false,
      showSelectOption: false,
      selectTimeData: {},
      currentData: {}, // 当前数据
      serviceAwardData: {}, // 服务奖
      achieveAwardData: {}, // 达标奖
      totalRegisterNum: 0,
      currentLoading: false,
      comeFrom: 0, // 0胜者定制 1徐鸿定制
      regionIndex: 0,
      xauId: '', //代理ID
    }
  },
  filters: {
    roleFilter(val) {
      var str = '';
      switch (val) {
        case 1:
          str = '正会长';
          break;
        case 2:
          str = '副会长';
          break;
        default:
          str = '未知';
          break;
      }
      return str;
    },
    achTypeFilter(val) {
      var typeObj = {
        1: '本月达标奖',
        3: '本季达标奖'
      };
      return typeObj[val];
    }
  },
  computed: {
    dataParentCss() { // 数据父元素的样式
      return 'c-w50 c-pv20';
    },
    dataNumberCss() { // 数据的数字样式
      return 'c-fs26 c-fc-xblack c-fw-b';
    },
    dataTextCss() { // 数据文字的样式
      return 'c-fs20 c-fc-gray c-mt8';
    },
    leftBorderCss() { // 标题左边标记的样式
      return 'c-ww5 c-hh16 theme-bg c-mr16 c-br4'
    },
    isCanGetCurrentData() { // 是否获取当前数据
      return this.selectItem.auId > 0 || this.selectItem.auId == -1
    },
    isNoAllCity() { // 不是全国
      return this.selectItem.auId > 0
    },
    showMoreAll() { // 是否展示下拉展开更多
      this.$nextTick(() => {
        var isShow = false
        if (this.$refs[`noticeSpan`].offsetHeight > this.$refs[`noticeDiv`].offsetHeight) {
          isShow = true
        } else {
          isShow = false
        }
        return isShow
      })
    }
  },
  watch: {

  },
  methods: {
    initData() { // 初始化数据
      this.getAreaUserPage().then(res => {
        // 申请审核通过的去获取达标奖等数据
        if (this.isCanGetCurrentData) { // 审核通过 或者是全国
          this.getCurrentData(); // 默认选择本月的数据
          if (this.isNoAllCity) {
            this.getServiceAward();
            this.getAchievementAward();
          }
        }
      }).catch(() => {

      })
    },
    getCurrentData() { // 获取当前数据
      var type = this.selectTimeData.type;
      var time = this.selectTimeData.value;
      var $this = this;
      if (this.currentLoading) {
        return;
      }
      this.currentLoading = true
      let url = this.comeFrom == 1 ? `xhAreaUser/getWxRewardDetail?xauId=${this.xauId}` : `areaUser/areaUserData?auId=${this.selectItem.auId}`
      utilJs.getMethod(global.apiurl + `${url}&type=${type}&time=${time}`,
        res => {
          $this.currentLoading = false
          if (res.data && res.data.length > 1) {
            res.data.sort((a, b) => { return a.prodType - b.prodType }) // 排个序 vip在前，svip在后
          }
          $this.currentData = res
        }, () => {
          $this.currentLoading = false
        }
      )
    },
    getServiceAward() { // 获取服务奖数据
      var $this = this;
      utilJs.getMethod(global.apiurl + `areaUser/getServiceAward?auId=${this.selectItem.auId}`, res => {
        $this.serviceAwardData = res.data;
        $this.totalRegisterNum = res.totalNum;
      }, () => {

      })
    },
    getAchievementAward() { // 获取达标奖 月 和季达标奖
      var $this = this;
      utilJs.getMethod(global.apiurl + `areaUser/getAchievementAward?auId=${this.selectItem.auId}`, res => {
        $this.achieveAwardData = res;
      }, () => {

      })
    },
    getAreaUserPage() {
      return new Promise((resolve, reject) => {
        var $this = this;
        let url = this.comeFrom == 1 ? 'xhAreaUser/getWxAreaUserList' : 'areaUser/areaUserPage';
        utilJs.getMethod(global.apiurl + url, res => {
          if (this.comeFrom == 0) {
            res.unshift({
              areaId: -1,
              areaUserApplicationId: -1,
              auId: -1,
              auditStatus: '',
              name: "全国",
              role: -1,
            })
          }
          $this.cityArr = res;
          if (this.comeFrom == 0) {
            if (!selectItemVal.areaUserApplicationId) { // 初始化没选中数据
              $this.changeCity($this.cityArr[0].areaId, $this.cityArr[0]) // 选择第一个申请的区
            }
          }
          // 当前数据的筛选，默认给0 3 近期 本月的数据
          this.selectTimeData = {
            type: 0,
            value: 3,
            label: '本月'
          }
          if (this.comeFrom == 1) {
            this.xauId = res[0].xauId;
            this.getCurrentData();
          }
          resolve()
        }, err => {
          reject(err)
        })
      })
    },
    changeCity(id, item) { // 切换城市
      if (this.currentLoading) {
        return;
      }
      this.showMoreInfo = false;
      selectItemVal = item
      this.selectItem = item
      var el = this.$el.querySelector('#city' + id);
      var cityScroll = this.$el.querySelector('#cityScroll');
      if (!el || !cityScroll) { return; }
      // 滑动效果
      let i = cityScroll.scrollLeft;
      var _this = this;
      clearInterval(_this.timer);
      if (i > el.offsetLeft) {
        this.timer = setInterval(function () {
          let left = i < el.offsetLeft + 100 ? el.offsetLeft : el.offsetLeft + 100;
          if (i < left) {
            clearInterval(_this.timer);
            return
          }
          i -= 20;
          cityScroll.scrollLeft = i;
        }, 10);
      } else {
        this.timer = setInterval(function () {
          let left = el.offsetLeft <= 0 ? 0 : el.offsetLeft - 100;
          if (i >= left) {
            clearInterval(_this.timer);
            return
          }
          i += 20;
          cityScroll.scrollLeft = i;
        }, 10);
      }
      if (this.isCanGetCurrentData) {
        this.selectTimeData = { // 切换城市的时候，给默认值本月
          type: 0,
          value: 3,
          label: '本月'
        }
        this.getCurrentData() // 获取当前数据
        if (this.isNoAllCity) {
          this.getServiceAward();
          this.getAchievementAward();
        }
      }
    },
    changeRegionType(index, xauId) {
      this.regionIndex = index;
      this.xauId = xauId;
      this.currentData = {};
      this.getCurrentData()
    },
    getData(data) { // 获取当前数据的方法，弹框消失
      this.showSelectOption = false;
      if (!data) { // 点击取消的情况
        return;
      }
      this.selectTimeData = data
      this.currentData = {};
      this.getCurrentData()
    },
    goAreaIncome() {
      this.$routerGo(this, "push", {
        path: "/homePage/newAreaUser/areaIncome",
        query: {
          comeFrom: 1
        }
      })
    },
    linkToIncome() { // 点击订单详情
      this.$routerGo(this, "push", {
        path: '/homePage/newAreaUser/areaIncome',
        query: {
          auId: this.selectItem.auId,
          comeFrom: this.comeFrom,
        }
      })
    },
    linkToCash() { // 点击去提现
      this.$routerGo(this, "push", {
        path: '/member/scholarship/scholarshipIndex'
      })
    },
    linkToApplyAreaAgent() { // 点击申请会长
      this.$routerGo(this, "push", {
        path: '/homePage/newAreaUser/apply',
        query: {
          from: 'apply',
          comeFrom: this.comeFrom,
        }
      })
    },
    linkToApplyRecords() { // 点击申请记录
      this.$routerGo(this, "push", {
        path: '/homePage/newAreaUser/applyRecords',
        query: {
          comeFrom: this.comeFrom,
        }
      })
    },

    //分享
    wechatShare: function () {
      let title = '区域会长';
      let shareImg = 'https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/common/provider.png';
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/newAreaUser/apply?comeFrom=${this.comeFrom}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = "点击查看详情";
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { }, true);
    },
      //手机端分享
    appShare: function () {
      utilJs.appShareTrue("", "", "", "");
    }
  },
  beforeRouteEnter(to, from, next) {
    fromPath = from.path;
    next();
  },
  activated() {
    setDocumentTitle('区域会长');// eslint-disable-line
    this.comeFrom = this.$route.query.comeFrom;
    this.regionIndex = 0;
    this.xauId = '';
    this.isAgentVipType().then(res => { // 验证服务商身份，不是的话跳转回个人中心
      var pathArr = ['/homePage/newAreaUser/areaIncome', '/member/scholarship/scholarshipIndex']
      if (!pathArr.some(el => fromPath.includes(el))) {
        selectItemVal = {}
        this.selectItem = {}
      }
      this.initData();
    })
    this.wechatShare();
  },
  deactivated() {

  }
}
</script>
<style scoped>
.section-icon {
  -moz-box-shadow: -6px 1px 10px #fff;
  -webkit-box-shadow: -6px 1px 10px #fff;
  box-shadow: -6px 1px 10px #fff;
  position: absolute;
  right: 0;
  z-index: 10;
  background-color: #fff;
}
</style>